<?php
namespace App\Http\Controllers\Admin;
use App\Models\Admins;
use Session;

class LoginController extends BaseController{

    public function __construct(Admins $admins)
    {
        parent::__construct();
        $this->admin = $admins;
    }



    public function getLogin()
    {
        if (Session::has('is_login')) {
            return redirect(urlAdmin('index','getIndex'));
        }
        return view('admin.login');

    }

    public function postLogin()
    {
        $inputs['username'] = request('username');
        $inputs['password'] = request('password');
        $inputs['captcha'] = request('captcha');
//        check_captcha($inputs['captcha']);
        //验证表单字段是否为空,如果方法有返回值则验证不通过
        $message = $this->checkFileds($inputs);
        $data['status'] = 0;
        if ($message) {
            $data['msg'] = $message;
            return response()->json($data);
        }
        $params = trim_fileds($inputs);
        $adminInfo = $this->admin->getLoginAdmin(request());
        if (empty($adminInfo)) {
            $data['msg'] = '用户名或密码错误';
            return ajax_return($data);
        }
        if ($adminInfo['state'] == 0) {
            $data['msg'] = '该用户已被禁用';
            return ajax_return($data);
        }
        if ($adminInfo['state'] == 0) {
            $data['msg'] = '该用户已被禁用';
            return ajax_return($data);
        }
        //更新用户登录信息
        $res = $this->admin->updateAdminLoginInfoById($adminInfo['id']);
        if (!$res) {
            $data['msg'] = '更新登录信息失败,请重新登陆';
            return ajax_return($data);
        }
        session(['admin'=>$adminInfo]);
        if ($adminInfo['is_super_admin'] == 1) {
            session(['is_super_admin'=>1]);
        }
        $data['status'] = 1;
        $data['msg'] = '登录成功！';
        $data['url'] = urlAdmin('index','getIndex');
        return ajax_return($data);
    }

    //验证表单字段是否为空
    public function checkFileds($inputs)
    {
        if (!$inputs['captcha']) {
            return '请填写验证码';
        }
        if (!$inputs['username']) {
            return '请填写用户名';
        }
        if (!$inputs['password']) {
            return '请填写密码';
        }
        if (!check_captcha($inputs['captcha'])) {
            return '验证码错误';
        }
    }

    public function getLogout()
    {
        Session::forget('is_login');
        Session::forget('uid');
        Session::forget('is_super_admin');
        return redirect(urlAdmin('login','getLogin'));
    }

}